<!-- #layout name=default -->
<div id="main">
  <div class="container-fluid">
    <div class="row">
      <div
        class="col-md-6 col-md-offset-3 col-sm-12 col-xs-12 margin-bottom-25"
      >
        <div>
          <template v-for="(item,index) in columns">
            <div :key="index" v-if="!item.isSystem" class="form-group">
              <label class="control-label">{{item.name}}</label>
              <div>
                <template v-if="item.isIncremental">
                  <p class="form-control-static">
                    {{(item.value || Kooboo.text.common.empty) + ' '}}-
                    <i
                      >{{' ('+
                      Kooboo.text.component.columnEditor.unableToChangeSelfIncrementField+')'}}</i
                    >
                  </p>
                </template>
                <template v-else>
                  <input
                    v-if="item.controlType=='TextBox'"
                    type="text"
                    class="form-control"
                    v-model="item.value"
                  />

                  <textarea
                    v-if="item.controlType=='TextArea'"
                    class="form-control"
                    v-model="item.value"
                  ></textarea>

                  <textarea
                    v-if="item.controlType=='Tinymce'"
                    v-kb-richeditor="richeditor(item.value)"
                    v-model="item.value"
                    style="opacity: 0"
                  ></textarea>

                  <select
                    v-if="item.controlType=='Selection'"
                    class="form-control"
                    v-model="item.value"
                  >
                    <option
                      v-for="opt in item.options"
                      :value="opt.value"
                      :key="opt.value"
                    >
                      {{opt.key}}
                    </option>
                  </select>

                  <template v-if="item.controlType=='CheckBox'">
                    <label
                      v-for="opt in item.options"
                      :key="opt.value"
                      class="checkbox-inline"
                    >
                      <input
                        type="checkbox"
                        :value="opt.value"
                        :checked="item.value.indexOf(opt.value)>-1"
                        @input="checkBoxInput(item.value,opt.value)"
                      />
                      <span>{{opt.key}}</span>
                    </label>
                  </template>

                  <template v-if="item.controlType=='RadioBox'">
                    <label
                      class="radio-inline"
                      v-for="opt in item.options"
                      :key="opt.value"
                    >
                      <input
                        type="radio"
                        :value="opt.value"
                        v-model="item.value"
                      />
                      <span>{{opt.key}}</span>
                    </label>
                  </template>

                  <label
                    class="checkbox-inline"
                    style="padding-left: 0"
                    v-if="item.controlType=='Boolean'"
                  >
                    <kb-switch type="checkbox" v-model="item.value" />
                  </label>

                  <input
                    v-if="item.controlType=='DateTime'"
                    type="datetime-local"
                    class="form-control"
                    v-model="item.value"
                  />

                  <input
                    v-if="item.controlType=='Number'"
                    type="number"
                    class="form-control"
                    v-model="item.value"
                  />
                </template>
              </div>
            </div>
          </template>
        </div>
        <kb-media-dialog :data.sync="mediaDialogData"></kb-media-dialog>
      </div>
    </div>
  </div>

  <div class="page-buttons">
    <button @click="onSave" class="btn green">Save</button>
    <a :href="dataPageUrl" class="btn gray">Cancel</a>
  </div>
</div>
<script>
  (function () {
    Kooboo.loadJS([
      "/_Admin/Scripts/kooboo/Guid.js",
      "/_Admin/Scripts/kooboo-web-editor/richEditor.min.js",
      "/_Admin/Scripts/components/tinymceMonaco/plugin.min.js",
      "/_Admin/Scripts/components/kb-media-dialog.js",
      "/_Admin/Scripts/lib/bootstrap-switch/bootstrap-switch.min.js",
      "/_Admin/Scripts/components/kbSwitch.js"
    ]);

    Kooboo.loadCSS(["/_Admin/Styles/bootstrap-datetimepicker.min.css",
      "/_Admin/Scripts/lib/bootstrap-switch/bootstrap-switch.min.css"]);
  })();

  new Vue({
    el: "#main",
    data: function() {
      return {
        columns: [],
        table: Kooboo.getQueryString("table"),
        id: Kooboo.getQueryString("id") || Kooboo.Guid.Empty,
        mediaDialogData: {}
      };
    },
    mounted: function() {
      var me = this;
      Kooboo.EventBus.subscribe("ko/style/list/pickimage/show", function(ctx) {
        Kooboo.Media.getList().then(function(res) {
          if (res.success) {
            res.model["show"] = true;
            res.model["context"] = ctx;
            res.model["onAdd"] = function(selected) {
              ctx.settings.file_browser_callback(
                ctx.field_name,
                selected.url + "?SiteId=" + Kooboo.getQueryString("SiteId"),
                ctx.type,
                ctx.win,
                true
              );
            };
            me.mediaDialogData = res.model;
          }
        });
      });
      Kooboo.Database.getEdit({
        tableName: me.table,
        id: me.id
      }).then(function(res) {
        if (res.success) {
          me.columns = res.model.map(function(data) {
            if (
              data.controlType &&
              data.controlType.toLowerCase() == "checkbox"
            ) {
              var value = null;
              if ($.isArray(data.value)) {
                value = data.value;
              } else {
                try {
                  value = JSON.parse(data.value);
                } catch (ex) {
                  value = [];
                }
              }
              data.value = value || [];
            } else if (
              data.controlType &&
              data.controlType.toLowerCase() == "tinymce"
            ) {
              data.value = data.value;
            } else if (
              data.controlType &&
              data.controlType.toLowerCase() == "datetime"
            ) {
              if (data.value && data.value.indexOf(".") > -1) {
                data.value = data.value.split(".")[0];
              }
            }

            var setting = JSON.parse(data.setting);
            if (setting && setting.options && setting.options.length) {
              data.options = setting.options;
              if (
                data.options &&
                data.options.length &&
                data.controlType &&
                data.controlType.toLowerCase() == "selection" &&
                !data.value
              ) {
                data.value = data.options[0].value;
              }
            }

            if (setting && setting.validations && setting.validations.length) {
              data.validations = setting.validations;
            }
            return data;
          });
        }
      });
    },
    methods: {
      richeditor: function(data) {
        var self = this;
        var item = {
          value: data,
          mediaDialogData: null
        };
        item = Vue.observable(item);
        this.$watch(
          function() {
            return item.mediaDialogData;
          },
          function(value) {
            self.mediaDialogData = value;
          }
        );

        return item;
      },
      onSave: function() {
        var me = this;
        var values = this.columns.map(function(col) {
          var value = col.value;

          if ($.isArray(col.value)) {
            value = JSON.stringify(col.value);
          }

          if (col.value && col.value.value) {
            value = col.value.value;
          }

          return {
            name: col.name,
            value: value
          };
        });

        Kooboo.Database.updateData({
          tableName: this.table,
          id: this.id,
          values: values
        }).then(function(res) {
          if (res.success) {
            location.href = me.dataPageUrl;
          }
        });
      },
      checkBoxInput(list, value) {
        var index = list.indexOf(value);
        if (index > -1) {
          list.splice(index, 1);
        } else {
          list.push(value);
        }
      }
    },
    computed: {
      dataPageUrl: function() {
        return Kooboo.Route.Get(Kooboo.Route.Database.DataPage, {
          table: this.table
        });
      }
    }
  });
</script>
